<template>
  <div class="m-data-config">
    <a-row class="item-box">
      <a-col :span="2">
        <div class="title">标题</div>
      </a-col>
      <a-col :span="22" style="text-align: right">
        <div class="describe">
          <a-input v-model:value="input.title" placeholder="请输入标题" @change="inputChange" />
        </div>
      </a-col>
    </a-row>
    <a-row class="item-box">
      <a-col :span="2"><div class="title">描述</div></a-col>
      <a-col :span="22" style="text-align: right">
        <div class="describe">
          <a-textarea
            placeholder="请输入描述"
            v-model:value="input.describe"
            @change="inputChange"
          />
        </div>
      </a-col>
    </a-row>

    <a-row class="item-box">
      <a-col :span="2">
        <div class="title">数据</div>
      </a-col>
      <a-col :span="22">
        <div class="radio-group">
          <a-radio-group v-model:value="dataSourceType">
            <a-radio :value="0">静态数据</a-radio>
            <a-radio :value="1">API</a-radio>
          </a-radio-group>
        </div>
      </a-col>
    </a-row>

    <div v-show="dataSourceType === 0">
      <div class="data-box" v-if="showData && showData.list">
        <div id="example1"></div>
      </div>
      <a-row class="item-box" v-if="showData && showData.value !== undefined">
        <a-col :span="2">
          <div class="title"></div>
        </a-col>
        <a-col :span="22">
          <a-input-number
            controls-position="right"
            v-model:value="showData.value"
            v-if="['gauge', 'liquid'].indexOf(type) > -1"
            :precision="2"
            :step="0.01"
            :max="1"
            :min="0"
            placeholder="请输入数据"
            @change="valueChange"
          />
          <a-input-number
            controls-position="right"
            v-else
            v-model:value="showData.value"
            placeholder="请输入数据"
            @change="valueChange"
          />
        </a-col>
      </a-row>
    </div>

    <Api v-show="dataSourceType === 1" :apiConfig="apiConfig" @api-change="apiChange"/>


  </div>
</template>
<script>
  import { defineComponent } from 'vue';
  import Handsontable from 'handsontable';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { random } from '@/utils/number.js';
  import Api from './api.vue'

  let handson = null;

  export default defineComponent({
    name: 'configData',
    components: { PlusOutlined, Api },
    props: {
      type: {
        type: String,
      },

      title: {
        type: String,
      },

      subtitle: {
        type: String,
      },

      describe: {
        type: String,
      },

      // 展示显示数据
      data: {
        type: Object,
        default: null,
      },

      // 数据源配置
      apiConfig: {
        type: Object,
      },

      // 数据源类型
      dataType: {
        type: Number,
      },
    },
    data() {
      return {
        input: {
          title: '',
          subtitle: '',
          describe: '',
        },

        showData: {},

        legend: [],

        dataSourceType: 0,

        // 表格数据
        tableData: [],
        colHeaders: [],

        rowIndex: 1,
        columnIndex: 1,
      };
    },

    created() {
      this.init();
    },

    mounted() {
      this.handsontable();
    },
    beforeUnmount() {
      handson && handson.destroy();
      handson = null;
    },

    methods: {
      init() {
        this.showData = this.data;
        this.dataSourceType = this.dataType;
        this.input = {
          title: this.title,
          subtitle: this.subtitle,
          describe: this.describe,
        };

        this.getTableData();
      },

      handsontable() {
        if (this.showData && this.showData.list) {
          let self = this;
          handson = new Handsontable(document.getElementById('example1'), {
            data: this.tableData,
            colWidths: 100,
            className: 'htCenter',
            rowHeaders: false,
            copyable: true,
            licenseKey: 'non-commercial-and-evaluation',
            afterChange: function (changes, source) {
              self.dataChange(changes);
            },
            // selected
            afterSelection(rowIndex, colIndex) {
              let obj = {}
              if (self.showData.axis) {
                let x = self.tableData[rowIndex][0], type = self.tableData[0][colIndex], value = self.tableData[rowIndex][colIndex]
                obj = {x, type, value}
              } else {
                obj = {
                  type: self.tableData[rowIndex][0],
                  value: self.tableData[rowIndex][colIndex]
                }
              }
              self.$emit('cell-selection', obj)
            },
            // 取消选中
            afterDeselect () {
              self.$emit('cell-selection', null)
            },
            contextMenu: {
              callback(key, options) {
                if (key === 'row_below') {
                  let start = options[0].start.row;
                  if (self.showData.axis) {
                    self.showData.axis.splice(start, 0, `row${self.rowIndex}`);
                    self.showData.list.forEach((o) => {
                      o.value.splice(start, 0, random(0, 1000));
                    });
                  } else {
                    start = start + 1;
                    self.showData.list.splice(start, 0, {
                      type: `row${self.rowIndex}`,
                      value: random(0, 1000),
                    });
                  }
                  self.getTableData();
                  handson.loadData(self.tableData);
                  self.rowIndex++;
                }

                if (key === 'col_right') {
                  let start = options[0].start.col;
                  let obj = { type: `column${self.columnIndex}`, value: [] };
                  self.showData.axis.forEach((o) => {
                    obj.value.push(random(0, 1000));
                  });
                  self.showData.list.splice(start, 0, obj);
                  self.getTableData();
                  handson.loadData(self.tableData);
                  self.columnIndex++;
                }

                if (key === 'remove_row') {
                  let start = options[0].start.row - 1,
                    end = options[0].end.row - start;
                  if (self.showData.axis) {
                    self.showData.axis.splice(start, end);
                    self.showData.list.forEach((o) => {
                      o.value.splice(start, end);
                    });
                  } else {
                    self.showData.list.splice(start, end);
                  }
                }
                if (key === 'remove_col') {
                  let start = options[0].start.col - 1,
                    end = options[0].end.col - start;
                  self.showData.list.splice(start, end);
                }
                self.$emit('data-change', self.showData);
              },
              items: {
                row_below: {
                  name: '在该行后插入行',
                },
                col_right: {
                  name: '在该列后插入列',
                  disabled() {
                    return !self.showData.axis;
                  },
                },
                remove_row: {
                  name: '删除该行',
                  disabled() {
                    let axis = self.showData.axis;
                    return this.getSelectedLast()[0] === 0 || (axis && axis.length <= 1);
                  },
                },
                remove_col: {
                  name: '删除该列',
                  disabled() {
                    return (
                      this.getSelectedLast()[1] === 0 ||
                      self.showData.list.length <= 1 ||
                      !self.showData.axis
                    );
                  },
                },
              },
            },
            beforeKeyDown: function (e) {
              // 禁止选中列后delete键和回退键清空整列数据
              if (e.keyCode === 8 || e.keyCode == 46) {
                e.stopImmediatePropagation();
              }
            },
          });
        }
      },

      // 选中单元格
      $selectCell(data) {
        let row = null, col = null

        if (!data.x) {
          this.tableData.forEach((o, i) => {
            if (o[0] === data.type) {
              row = i
              o.forEach((v, j) => {
                if (v === data.value) {
                  col = j
                }
              })
            }
          })
        } else {
          this.tableData[0].forEach((o, i) => {
            if (o === data.type) {
              col = i
            }
          })
          this.tableData.forEach((o, i) => {
            if (o[0] === data.x) {
              row = i
            }
          })
        }
        
        if (row !== null && col !== null) {
          handson.selectCell(row, col);
        }
      },

      // 获取表格数据
      getTableData() {
        let legend = [];
        this.showData.list &&
          this.showData.list.forEach((o) => {
            legend.push(o.type);
          });

        this.legend = legend;
        this.colHeaders = ['轴', ...legend];
        const tableData = [],
          showData = this.showData;

        if (showData.axis) {
          tableData.push(this.colHeaders);
          showData.axis.forEach((o, i) => {
            let arr = [o];
            showData.list.forEach((v) => {
              arr.push(v.value[i]);
            });
            tableData.push(arr);
          });
        } else if (!showData.axis && showData.list) {
          showData.list.forEach((o) => {
            let arr = [];
            arr.push(o.type, o.value);
            tableData.push(arr);
          });
        }
        this.tableData = tableData;
      },

      // 数据改变
      dataChange(v) {
        let showData = this.showData;
        if (v) {
          let isChange = false;
          v.forEach((arr) => {
            const newValue = arr[3],
              value = arr[2],
              rowIndex = arr[0],
              colIndex = arr[1];
            if (newValue != value) {
              isChange = true;

              if (showData.axis) {
                if (rowIndex === 0 && colIndex > 0) {
                  // 修改类型
                  showData.list[colIndex - 1].type = newValue;
                } else if (colIndex === 0 && rowIndex > 0) {
                  // 修改轴
                  showData.axis[rowIndex - 1] = newValue;
                } else {
                  //修改数据
                  showData.list[colIndex - 1].value[rowIndex - 1] = +newValue;
                }
              } else if (!showData.axis && showData.list) {
                const dataItem = showData.list[rowIndex];
                colIndex > 0 ? (dataItem.value = +newValue) : (dataItem.type = newValue);
              }
            }
          });

          if (isChange) {
            this.$emit('data-change', this.showData);
          }
        }
      },

      valueChange(currentValue) {
        this.$emit('data-change', this.showData);
      },

      inputChange(v, key) {
        this.$emit('input-change', this.input);
      },

      apiChange (v) {
        this.$emit('api-change', v)
      }
    },
  });
</script>
<style lang="scss">
  #hot-display-license-info {
    display: none;
  }
  .m-data-config {
    font-size: 12px;
    .item-box {
      margin-bottom: 10px;
      .title {
        font-size: 12px;
        padding-top: 5px;
      }
      .describe {
        padding-right: 10px;
      }
      .radio-group {
        padding-top: 3px;
        .ant-radio-wrapper {
          font-size: 12px;
        }
      }
    }
    .data-box {
      #example1 {
        display: inline-block;
        .ht_master {
          display: inline-block;
          .wtHolder {
            width: inherit !important;
            height: inherit !important;
            display: inline-block;
          }
        }
      }

      .row-push {
        cursor: pointer;
        display: inline-block;
      }
    }
  }
</style>
